package com.metronoteapp;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import com.metronoteapp.adapter.AllNoteAdapter;
import com.metronoteapp.database.DBHelper;
import com.metronoteapp.database.NoteDao;
import com.metronoteapp.dialog.DialogAboutClient;
import com.metronoteapp.dialog.DialogClient;
import com.metronoteapp.dialog.DialogMenuClient;
import com.metronoteapp.dialog.RecordingAudioDialog;
import com.metronoteapp.model.NoteModel;
import com.metronoteapp.until.Constants;

public class MainActivity extends Activity implements OnClickListener {
	private String TAG = MainActivity.class.getSimpleName();
	private Context mContext;
	private ListView mListViewNote;
	private DBHelper mDBHelper;
	private ImageView btnExit;
	private ImageView btnAbout;
	private ImageView btnAudioRecord;
	private ImageView btnGroup;
	private ImageView btnImp;
	private ImageView btnAdd;
	private EditText txtSearch;
	private LinearLayout mLinearSearch;
	private LinearLayout mLinearGroup;
	private AllNoteAdapter mAdapterNote;
	private List<NoteModel> mListObjNote;
	private NoteModel mObjNoteModel;
	private NoteDao mObjNoteDao;
	private Boolean blnShowAllImp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_metro_note);

		// Set full Screen activity
		WindowManager.LayoutParams attrs = this.getWindow().getAttributes();
		attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
		this.getWindow().setAttributes(attrs);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		blnShowAllImp = false;

		// Initiaze object
		mContext = this;
		mDBHelper = new DBHelper(mContext);
		btnExit = (ImageView) findViewById(R.id.btnExitMetro);
		btnAbout = (ImageView) findViewById(R.id.btnAboutMetro);
		btnAudioRecord = (ImageView) findViewById(R.id.btnAudioMetro);
		btnGroup = (ImageView) findViewById(R.id.btnGroupMetro);
		btnImp = (ImageView) findViewById(R.id.btnImpMetro);
		btnAdd = (ImageView) findViewById(R.id.btnAddMetro);
		txtSearch = (EditText) findViewById(R.id.txtFilter);
		mLinearSearch = (LinearLayout) findViewById(R.id.paneSearch);
		mLinearSearch.setVisibility(LinearLayout.VISIBLE);
		mListViewNote = (ListView) findViewById(R.id.lvNoteMain);

		// Create folder
		File direct = new File(com.metronoteapp.until.Constants.PATH_DATA);
		Log.v(TAG, com.metronoteapp.until.Constants.PATH_DATA);
		if (!direct.exists()) {
			if (direct.mkdir()) {
				Log.v(TAG, "Created folder: "
						+ com.metronoteapp.until.Constants.PATH_DATA);
			} else {
				Log.v(TAG, "Created Failed!" + direct.getParent());
			}

		} else {
			Log.v(TAG, "takePhoto() | Folder exist");
		}

		showAdapterAllNote();
		registerForContextMenu(mListViewNote);

		txtSearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				MainActivity.this.mAdapterNote.filter(s);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		// // Handle DONE
		// txtSearch.setOnEditorActionListener(new OnEditorActionListener() {
		// @Override
		// public boolean onEditorAction(TextView v, int actionId,
		// KeyEvent event) {
		// if (actionId == EditorInfo.IME_ACTION_DONE) {
		// mAdapterNote.filter(txtSearch.getText().toString()
		// .toLowerCase());
		// }
		// return false;
		// }
		// });

		// Set on click listener
		btnExit.setOnClickListener(this);
		btnAbout.setOnClickListener(this);
		btnAudioRecord.setOnClickListener(this);
		btnGroup.setOnClickListener(this);
		btnImp.setOnClickListener(this);
		btnAdd.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			onBackPressed();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	public void onBackPressed() {
		DialogClient objDialog = new DialogClient(mContext);
		objDialog.displaydialog("Do you really want to exit?",
				Constants.TYPE_EXIT_APP, "");
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnExitMetro:
			DialogClient objDialog = new DialogClient(mContext);
			objDialog.displaydialog("Do you really want to exit?",
					Constants.TYPE_EXIT_APP, "");
			break;
		case R.id.btnAddMetro:
			DialogMenuClient newObjMenu = new DialogMenuClient(mContext);
			newObjMenu.displaydialog();
			break;
		case R.id.btnImpMetro:
			if (blnShowAllImp == true) {
				this.showAdapterAllNoteImpt();
			} else {
				this.showAdapterAllNote();
			}
			break;
		case R.id.btnAboutMetro:
			DialogAboutClient objAbout = new DialogAboutClient(mContext);
			objAbout.displaydialog();
			break;
		case R.id.btnGroupMetro:
			Intent callExpandNote = new Intent(mContext, GroupExpActivity.class);
			mContext.startActivity(callExpandNote);
			break;
		case R.id.btnAudioMetro:
			RecordingAudioDialog objRecording = new RecordingAudioDialog(
					mContext);
			objRecording.displaydialog();
			break;
		default:
			break;
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.lvNoteMain) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			menu.setHeaderTitle("Option");
			String[] menuItems = getResources().getStringArray(R.array.menu);
			for (int i = 0; i < menuItems.length; i++) {
				menu.add(Menu.NONE, i, i, menuItems[i]);
			}
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		int menuItemIndex = item.getItemId();
		String[] menuItems = getResources().getStringArray(R.array.menu);
		String menuItemName = menuItems[menuItemIndex];
		mObjNoteModel = new NoteModel();
		mObjNoteModel = mListObjNote.get(info.position);
		if (menuItemName.equalsIgnoreCase("Edit")) {
			editNote(mObjNoteModel);
		} else if (menuItemName.equalsIgnoreCase("Delete")) {
			deleteNote(mObjNoteModel);
		} else {
			updateImportant(mObjNoteModel);
		}
		return true;
	}

	/*
	 * This function update importand flag
	 */
	private void updateImportant(NoteModel _obj) {
		mObjNoteDao = new NoteDao(mContext);
		if (_obj.getFlgFav() == 1) {
			_obj.setFlgFav(0);
		} else {
			_obj.setFlgFav(1);
		}
		mObjNoteDao.openDB();
		Long lngResult = mObjNoteDao.updateNote(_obj);
		if (lngResult == 1) {
			Intent callMainNote = new Intent(mContext, MainActivity.class);
			mContext.startActivity(callMainNote);
		} else {
			Toast.makeText(mContext, "Error!", Toast.LENGTH_SHORT).show();
		}
		mObjNoteDao.closeDB();
	}

	/*
	 * This function edit one note
	 */
	private void editNote(NoteModel _obj) {
		if (_obj.getNoteType().equalsIgnoreCase(Constants.TYPE_TEXT)) {
			Intent callAddNote = new Intent(mContext, AddNoteActivity.class);
			callAddNote.putExtra("NoteId", String.valueOf(_obj.getId()));
			callAddNote.putExtra("FlgImp", String.valueOf(_obj.getFlgFav()));
			mContext.startActivity(callAddNote);
		} else {
			Toast.makeText(mContext,
					"Infor: Only TEXT NOTE can editting by this way!",
					Toast.LENGTH_SHORT).show();
		}
	}

	/*
	 * This function delete one note
	 */
	private void deleteNote(NoteModel _obj) {
		String pathAudio = "";
		if (_obj.getNoteType().equalsIgnoreCase(Constants.TYPE_AUDIO)) {
			pathAudio = _obj.getContent();
		}
		mObjNoteDao = new NoteDao(mContext);
		mObjNoteDao.openDB();
		Boolean blnResult = mObjNoteDao.removeNote(_obj);
		if (blnResult == true) {
			if (!pathAudio.equalsIgnoreCase("")) {
				File direct = new File(pathAudio);
				Log.v(TAG, "Path delete: " + pathAudio);
				if (direct.exists()) {
					direct.delete();
				}
			}
			Intent callMainNote = new Intent(mContext, MainActivity.class);
			mContext.startActivity(callMainNote);
		} else {
			Toast.makeText(mContext, "Error!", Toast.LENGTH_SHORT).show();
		}
		mObjNoteDao.closeDB();
	}

	/*
	 * This function parse cursor
	 */
	private static String getColumnAsString(Cursor cursor, int index) {
		return cursor.getString(index).trim();
	}

	/*
	 * This function set adapter for listview main - NOTE!
	 */
	private void showAdapterAllNote() {
		mListObjNote = new ArrayList<NoteModel>();
		mObjNoteDao = new NoteDao(mContext);
		mObjNoteDao.openDB();
		Cursor mCursor = mObjNoteDao.getAllRecord();
		if (mCursor.moveToFirst()) {
			do {
				mObjNoteModel = new NoteModel();
				mObjNoteModel.setId(Integer.parseInt(getColumnAsString(mCursor,
						0)));
				mObjNoteModel.setTitle(getColumnAsString(mCursor, 1));
				mObjNoteModel.setContent(getColumnAsString(mCursor, 2));
				mObjNoteModel.setNoteType(getColumnAsString(mCursor, 3));
				mObjNoteModel.setDateTime(getColumnAsString(mCursor, 4));
				mObjNoteModel.setGroupId(Integer.parseInt(getColumnAsString(
						mCursor, 5)));
				mObjNoteModel.setFlgFav(Integer.parseInt(getColumnAsString(
						mCursor, 6)));
				mListObjNote.add(mObjNoteModel);
			} while (mCursor.moveToNext());
		}
		mObjNoteDao.closeDB();
		mAdapterNote = new AllNoteAdapter(mContext, mListObjNote);
		mListViewNote.setAdapter(mAdapterNote);
		mListViewNote.setOnItemClickListener(mAdapterNote);
		btnImp.setBackgroundResource(R.drawable.filter);
		blnShowAllImp = true;
	}

	/*
	 * This function set adapter for listview main - NOTE!
	 */
	private void showAdapterAllNoteImpt() {
		mListObjNote = new ArrayList<NoteModel>();
		mObjNoteDao = new NoteDao(mContext);
		mObjNoteDao.openDB();
		Cursor mCursor = mObjNoteDao.getNoteImportant();
		if (mCursor.moveToFirst()) {
			do {
				mObjNoteModel = new NoteModel();
				mObjNoteModel.setId(Integer.parseInt(getColumnAsString(mCursor,
						0)));
				mObjNoteModel.setTitle(getColumnAsString(mCursor, 1));
				mObjNoteModel.setContent(getColumnAsString(mCursor, 2));
				mObjNoteModel.setNoteType(getColumnAsString(mCursor, 3));
				mObjNoteModel.setDateTime(getColumnAsString(mCursor, 4));
				mObjNoteModel.setGroupId(Integer.parseInt(getColumnAsString(
						mCursor, 5)));
				mObjNoteModel.setFlgFav(Integer.parseInt(getColumnAsString(
						mCursor, 6)));
				mListObjNote.add(mObjNoteModel);
			} while (mCursor.moveToNext());
		}
		mObjNoteDao.closeDB();
		mAdapterNote = new AllNoteAdapter(mContext, mListObjNote);
		mListViewNote.setAdapter(mAdapterNote);
		mListViewNote.setOnItemClickListener(mAdapterNote);
		btnImp.setBackgroundResource(R.drawable.showall);
		blnShowAllImp = false;
	}
}
